<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
    >
      <el-form-item label="领用号" prop="receiveCode">
        <el-input
            v-model="queryParams.receiveCode"
            placeholder="请输入领用号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="申请标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入申请标题"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="审批结果" prop="status">
        <el-select
            v-model="queryParams.status"
            placeholder="请选择审批结果"
            clearable
            class="!w-240px"
        >
          <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="领用号" align="center" prop="receiveCode" />
      <el-table-column label="申请人" align="center" prop="userName" />
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="申请标题" align="center" prop="title" />
      <el-table-column label="审批结果" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="发放状态" align="center" prop="issueStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.issueStatus === 0" type="warning">未发放</el-tag>
          <el-tag v-else-if="scope.row.issueStatus === 1" type="success">已发放</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
      />
      <el-table-column label="操作" align="center" min-width="160px">
        <template #default="scope">
          <el-button
              v-hasPermi="['oa:material-receive:query']"
              link
              type="primary"
              @click="handleDetail(scope.row)"
          >
            详情
          </el-button> 
          <!-- <el-button
              v-hasPermi="['oa:material-receive:query']"
              link
              type="primary"
              @click="handleProcessDetail(scope.row)"
          >
            进度
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

  <DetailDrawer
    v-model="showDetailDrawer"
    :task-id="currentMaterialReceiveId"
    title="物品领用详情" />

  <ProcessInstanceDetailDrawer
    v-model="showDrawer" :process-instance-id="currentProcessInstanceId" title="流程进度"
    @success="handleDrawerSuccess" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { MaterialReceiveApi, MaterialReceiveVO } from '@/api/oa/materialreceive'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import ProcessInstanceDetailDrawer from '@/views/bpm/processInstance/components/ProcessInstanceDetailDrawer.vue'
import DetailDrawer from '@/views/oa/materialreceive/components/DetailDrawer.vue'

/** 本部门物品领用 列表 */
defineOptions({ name: 'MaterialReceiveDeptIndex' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<MaterialReceiveVO[]>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  receiveCode: undefined,
  title: undefined,
  status: undefined,
})
const queryFormRef = ref() // 搜索的表单
const showDetailDrawer = ref(false)
const currentMaterialReceiveId = ref<number | undefined>(undefined)

const showDrawer = ref(false)
const currentProcessInstanceId = ref('')

const handleDrawerSuccess = () => {
  showDrawer.value = false
  getList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MaterialReceiveApi.getDeptMaterialReceivePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 详情操作 */
const handleDetail = (row: MaterialReceiveVO) => {
  currentMaterialReceiveId.value = row.id
  showDetailDrawer.value = true
}

/** 审批进度 */
const handleProcessDetail = (row: MaterialReceiveVO) => {
  currentProcessInstanceId.value = row.processInstanceId
  showDrawer.value = true
}

/** 发放操作 */
const handleIssue = async (row: MaterialReceiveVO) => {
  try {
    // 二次确认
    await ElMessageBox.confirm('确认要发放该物品吗？发放后将扣减库存。', '发放确认', {
      confirmButtonText: '确认发放',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 调用发放接口
    await MaterialReceiveApi.issueMaterialReceive(row.id)
    message.success('发放成功')
    // 刷新列表
    await getList()
  } catch (error) {
    // 用户取消或发放失败
    if (error !== 'cancel') {
      console.error('发放失败:', error)
    }
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script> 